package com.example.redistokendemo.annotation;

import com.example.redistokendemo.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 接口幂等性拦截器
 *
 * @author wanghuajun
 * @version 1.0
 * @date 2019-08-11 20:27
 */
@Slf4j
public class ApiIdempotentInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        ApiIdempotent annotation = method.getAnnotation(ApiIdempotent.class);
        if (annotation != null) {
            //校验幂等性，如果通过自然放行，并删除缓存中的token，否则抛异常
            try {
                tokenUtil.checkToken(request);
            } catch (Exception e) {
                log.error("校验token异常=====重定向到token接口====>{}", e.getMessage());
                response.sendRedirect("/token");
                return false;
            }
        }

        return true;
    }

}
